package com.grupoconstruobras.sigo.exhumaciones.ui.validator;

import java.io.Serializable;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class LongitudePattern implements Validator, Serializable {
	
	//@ManagedProperty("#{msgVal}")
	private ResourceBundle bundle;
	
	public LongitudePattern() {
		FacesContext fc = FacesContext.getCurrentInstance();
		bundle = fc.getApplication().evaluateExpressionGet(fc, "#{msgVal}", ResourceBundle.class);
	}

	@Override
	public void validate(FacesContext fc, UIComponent component, Object value)
			throws ValidatorException {
		/*if(value == null) {
			String msg = bundle.getString("constraint.not_null");
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, name + msg, null);
			fc.addMessage(component.getClientId(), message);
			throw new ValidatorException(message);
		}*/
		
		if(value == null) {
			return;
		}
		
		String localizacion = (String) value;
		if(localizacion.length() > 15) {
			String msg = bundle.getString("constraint.size.max");
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg + " 15", null);
			fc.addMessage(component.getClientId(), message);
			throw new ValidatorException(message);
		}
		//(([01][0-7]|[00][0-9])[0-9]|[1][8][0])° [0-9][0-9]\.[0-9]´ [EW] - Longitude
		Pattern pattern = Pattern.compile("(^$(([01][0-7]|[00][0-9])[0-9]|[1][8][0])° [0-9][0-9]\\.[0-9]´ [eEwW])");
		Matcher matcher = pattern.matcher(localizacion);
		if(!matcher.matches()) {
			String msg = bundle.getString("constraint.pattern.localizacion");
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, null);
			fc.addMessage(component.getClientId(), message);
			throw new ValidatorException(message);
		}
		
	}

}
